package com.iot.manager.ui.activities;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.iot.manager.R;
import com.iot.manager.data.models.Device;
import com.iot.manager.data.models.LoginRequest;
import com.iot.manager.data.models.LoginResponse;
import com.iot.manager.network.ApiService;
import com.iot.manager.network.RetrofitClient;
import com.iot.manager.network.WebSocketManager;
import com.iot.manager.utils.SharedPreferencesManager;
import com.iot.manager.MainActivity;
import com.iot.manager.data.models.UserManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {
    private EditText etEmail;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnRegister;
    private ApiService apiService;
    private SharedPreferencesManager sharedPreferencesManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 初始化SharedPreferencesManager
        sharedPreferencesManager = SharedPreferencesManager.getInstance(this);
        
        // 检查是否已登录
        if (sharedPreferencesManager.isLoggedIn()) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
            return;
        }
        
        setContentView(R.layout.activity_login);

        apiService = RetrofitClient.getInstance().getApiService();

        etEmail = findViewById(R.id.etEmail);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        btnRegister = findViewById(R.id.btnRegister);

        btnLogin.setOnClickListener(v -> login());
        btnRegister.setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
        });
    }

    private void login() {
        String email = etEmail.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (email.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, R.string.login_empty_fields, Toast.LENGTH_SHORT).show();
            return;
        }

        LoginRequest request = new LoginRequest(email, password);
        apiService.login(request).enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    LoginResponse loginResponse = response.body();
                    handleLoginSuccess(loginResponse);
                } else {
                    runOnUiThread(() -> Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show());
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                runOnUiThread(() -> Toast.makeText(LoginActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show());
            }
        });
    }

    private void handleLoginSuccess(LoginResponse response) {
        String token = response.getToken();
        
        // 使用SharedPreferencesManager保存登录信息
        sharedPreferencesManager.saveLoginInfo(
            token,
            response.getId(),
            response.getUsername(),
            response.getEmail(),
            response.getRole()
        );
        
        // 使用UserManager保存登录信息
        UserManager.getInstance().saveToken(token);
        UserManager.getInstance().saveUserInfo(
            response.getId(),
            response.getUsername(),
            response.getEmail(),
            response.getRole()
        );
        
        // 设置RetrofitClient的token
        RetrofitClient.getInstance().setToken(token);
        
        // 连接WebSocket
        WebSocketManager.getInstance(this).connect(token);
        
        // 跳转到主页
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
} 